package com.hll.javaweb.servlet.cookie;

import com.alibaba.fastjson.JSON;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hll
 * @create 2022-05-10 13:53
 */
@WebServlet("/cookie-write")
public class CookieWrite extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Cookie cookie = new Cookie("username", "abc");
    // setMaxAge(-1) //设置为负数表示当前会话有效。也就是关闭浏览器后 Cookie 失效
    // setMaxAge(0) // 表示马上删除，都不需要等待浏览器关闭
    cookie.setMaxAge(60 * 60 * 24); // 秒为单位,一天后过期
    // 设置访问那些路径会携带cookie --- 此时  /web/*
    cookie.setPath(getServletContext().getContextPath() + "/");
    resp.addCookie(cookie); // 可以add多个
    resp.getWriter().write(JSON.toJSONString(cookie));
  }
}
